<template>
  <el-table :data="tableData" border>
    <el-table-column prop="alipayAccount" label="支付宝账号" width="220" align="center">
      <template #default="scope">
        <el-input v-model="scope.row.alipayAccount"></el-input>
      </template>
    </el-table-column>
    <el-table-column prop="alipayName" label="支付宝名称" width="220" align="center">
      <template #default="scope">
        <el-input v-model="scope.row.alipayName"></el-input>
      </template>
    </el-table-column>
    <el-table-column prop="independentAccountProportion" label="分账比例" width="120" align="center">
      <template #default="scope">
        <el-input v-model="scope.row.independentAccountProportion" type="number">
          <template #suffix>
            <span>%</span>
          </template>
        </el-input>
      </template>
    </el-table-column>
    <el-table-column prop="time" label="分账有效期" align="center">
      <template #default="scope">
      <el-date-picker
          @change="onChange(scope.row, $event)"
          v-model='scope.row.time'
          type='daterange'
          range-separator='至'
          start-placeholder='开始日期'
          end-placeholder='结束日期'>
      </el-date-picker>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="60">
      <template #default="scope">
        <div @click="onAdd" v-if="scope.$index == 0">
          <el-icon><CirclePlusFilled /></el-icon>
        </div>
        <div @click="onRemove(scope.$index)" v-if="scope.$index > 0">
          <el-icon><RemoveFilled /></el-icon>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>

import {watch} from "vue";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => {return []}
  },
})

const tableData = ref([])

const onAdd = () => {
  tableData.value.push({alipayAccount: "", alipayName: "", independentAccountProportion: "0"});
}

const onRemove = (index) => {
  tableData.value.splice(index, 1);
}

const onChange = (data, e) => {
  data.effectiveBeginTime = Helper.formatDate(e[0], 'yyyy-MM-dd');
  data.effectiveEndTime = Helper.formatDate(e[1], 'yyyy-MM-dd');
}

watch(() => props.modelValue, (value) => {
  if(Helper.emptyArray(value)) {
    value = [];
  }

  value.forEach(v => {
    if(!Helper.empty(v.effectiveBeginTime) && !Helper.empty(v.effectiveEndTime)) {
      v.time = [v.effectiveBeginTime, v.effectiveEndTime];
    }
  })

  tableData.value = value;
}, {immediate: true})
const emit = defineEmits(['update:modelValue'])
watch(() => tableData.value, (data) => {
  emit('update:modelValue', data);
})

</script>

<style scoped>

</style>
